package com.chengliang.bbs.service.impl;

import com.chengliang.bbs.entry.Message;
import com.chengliang.bbs.entry.MessageTemplate;
import com.chengliang.bbs.entry.User;
import com.chengliang.bbs.entry.UserAuths;
import com.chengliang.bbs.mapper.*;
import com.chengliang.bbs.service.UserService;
import com.chengliang.bbs.type.UserIdentityType;
import com.chengliang.bbs.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

/**
 * @author: chengliang
 * @create: 2019-07-24 11:03
 */
@Service
@Slf4j
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    private final UserAuthsMapper authsMapper;

    private final PasswordEncoder passwordEncoder;

    private final MessageMapper messageMapper;

    private final ContinuityPracticeMapper continuityPracticeMapper;

    private final ExperienceMapper experienceMapper;

    public UserServiceImpl(UserMapper userMapper, UserAuthsMapper authsMapper, PasswordEncoder passwordEncoder, MessageMapper messageMapper, ContinuityPracticeMapper continuityPracticeMapper, ExperienceMapper experienceMapper) {
        this.userMapper = userMapper;
        this.authsMapper = authsMapper;
        this.passwordEncoder = passwordEncoder;
        this.messageMapper = messageMapper;
        this.continuityPracticeMapper = continuityPracticeMapper;
        this.experienceMapper = experienceMapper;
    }

    @Override
    public User getUserByUserId(Integer userId) {
        return userMapper.selectUserByUserId(userId);
    }

    @Override
    public boolean isQQBind(Integer userId) {
        return authsMapper.selectIsIdentityTypeBind(userId,UserIdentityType.qq) != null;
    }

    @Override
    public boolean updatePasswordByNickName(String nickName,String password) {
        if(StringUtil.isEmpty(nickName) || StringUtil.isEmpty(password)){
            return false;
        }
        //通过昵称查询用户信息
        User user = userMapper.selectUserByNickName(nickName);
        if(StringUtil.isEmpty(user)){
            log.error("修改密码：昵称{},未查询到用户信息",nickName);
            return false;
        }
        //密码加密
        String encodePassword = passwordEncoder.encode(password);
        //修改密码
        return authsMapper.updateUserCredentialByUserId(user.getUserId(), encodePassword);
    }

    @Override
    public String getNickNameByLoginName(String loginName) {
        return userMapper.selectNickNameByEmail(loginName);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean register(User user, UserAuths userAuths) {
        //注册方式
        UserIdentityType userIdentityType = userAuths.getUserIdentityType();
        switch (userIdentityType){
            case email:
                user.setUserEmail(userAuths.getUserIdentifier());
                break;
            case phone:
                user.setUserPhone(userAuths.getUserIdentifier());
                break;
        }
        int insertSelective=1;

        //无ID信息
        if(StringUtil.isEmpty(userAuths.getUser()) || StringUtil.isEmpty(userAuths.getUser().getUserId())){
            log.debug("添加用户信息前:{}",user);
            //添加用户信息
            insertSelective = userMapper.insertSelective(user
                    //设置默认头像
                    .setUserAvatar(StringUtil.isEmpty(user.getUserAvatar())?"/res/images/avatar/default.png":user.getUserAvatar())
                    //设置null值防止用户传递错误信息影响系统
                    .setUserId(null).setUserRegisterTime(null));
            log.debug("添加用户信息后:{}",user);
            //初始化经验信息
            experienceMapper.init(user.getUserId());
            //发送消息
            messageMapper.insertMessage(new Message().setJieId(0).setProduceUserId(0).setMessageContent(MessageTemplate.systemTemplate("欢迎使用 程亮云社区")).setReceiverUserId(user.getUserId()));
            //初始化签到信息
            continuityPracticeMapper.init(user.getUserId());
        }
        //添加权限信息
        int insertSelective1 = authsMapper.insertSelective(userAuths
                //关联用户ID
                .setUserId(user.getUserId())
                .setUser(user)
                //密码加密
                .setUserCredential(passwordEncoder.encode(userAuths.getUserCredential()))
                //防止用户传递该参数
                .setUserAuthsId(null).setUserAuthorities("user"));
        return true;
    }

    @Override
    public boolean isExistsUserNickName(String nickName) {
        if(StringUtils.isEmpty(nickName)){
            return false;
        }
        return userMapper.isExistsUserNickName(nickName) != null;
    }

    @Override
    public boolean isExistsUserLoginName(String loginName) {
        if(StringUtils.isEmpty(loginName)){
            return false;
        }
        return userMapper.isExistsEmailOrPhone(loginName) != null;
    }

    @Override
    public boolean updateUserInfoByUserId(User user) {
        return userMapper.updateByPrimaryKeySelective(user
                //字段置null防止用户修改。
                .setUserRegisterTime(null).setUserIsEnable(null).setUserNickName(null))>0;
    }

    @Override
    public boolean unbind(Integer userId, UserIdentityType identityType) {
        UserAuths userAuths = new UserAuths().setUserId(userId);
        //登录方式至少留一种
        int i = authsMapper.selectCount(userAuths);
        if(i<=1){
            return false;
        }
        return authsMapper.delete(userAuths.setUserIdentityType(identityType))>0;
    }

    @Override
    public User getUserByNickName(String userNickName) {
        if(StringUtil.isEmpty(userNickName)){
            return null;
        }
        return userMapper.selectUserByNickName(userNickName);
    }

}
